package com.gitee.feizns.dynamic;

import java.util.ArrayList;
import java.util.List;

/**
 * <b>{@link List}操作工具类</b>
 * @author feizns
 * @since 2023/3/14
 */
public abstract class ListUtils {

    /**
     * <b>将list切割为每size一份</b>
     * <pre>{@code
     *  List<User> users = userRepository.findAll();
     *  //按每50个一组分割
     *  List<List<User>> parts = ListUtils.partition(users, 50);
     *  parts.stream().forEach(list -> {
     *     process(list);
     *  });
     * }</pre>
     * @param list {@link List}
     * @param size 切割大小
     * @return 切割后的每份集合
     * @param <T> 元素类型
     */
    public static <T> List<List<T>> partition(List<T> list, int size) {
        int listSize = list.size();
        int stepSize = listSize % size == 0 ? listSize / size : (listSize / size) + 1;
        List<List<T>> resultList = new ArrayList<>();
        for (int i = 0; i < stepSize; i++) {
            int fromIndex = i * size;
            int endIndex = (i + 1) * size;
            if (endIndex > listSize)
                endIndex = listSize;
            resultList.add(list.subList(fromIndex, endIndex));
        }
        return resultList;
    }

}
